package com.ruoyi.system.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.AiConversation;
import com.ruoyi.system.service.IAiAssistantService;

/**
 * AI智能助手Controller
 * 
 * @author ruoyi
 * @date 2025-01-21
 */
@RestController
@RequestMapping("/system/ai")
public class AiAssistantController extends BaseController
{
    @Autowired
    private IAiAssistantService aiAssistantService;

    /**
     * 获取AI编程提示
     */
    @PreAuthorize("@ss.hasPermi('system:ai:hint')")
    @PostMapping("/hint")
    public AjaxResult getAiHint(@RequestBody Map<String, Object> requestData)
    {
        try {
            String problemId = (String) requestData.get("problemId");
            String questionType = (String) requestData.get("questionType");
            String userCode = (String) requestData.get("userCode");
            String language = (String) requestData.get("language");
            
            // 调用AI服务获取提示
            String hint = aiAssistantService.getProgrammingHint(problemId, questionType, userCode, language);
            
            Map<String, Object> result = new HashMap<>();
            result.put("hint", hint);
            result.put("questionType", questionType);
            result.put("timestamp", System.currentTimeMillis());
            
            return success(result);
        } catch (Exception e) {
            return error("获取AI提示失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI代码分析
     */
    @PreAuthorize("@ss.hasPermi('system:ai:analysis')")
    @PostMapping("/analysis")
    public AjaxResult getAiAnalysis(@RequestBody Map<String, Object> requestData)
    {
        try {
            String problemId = (String) requestData.get("problemId");
            String userCode = (String) requestData.get("userCode");
            String language = (String) requestData.get("language");
            
            // 调用AI服务进行代码分析
            Map<String, Object> analysis = aiAssistantService.analyzeCode(problemId, userCode, language);
            
            return success(analysis);
        } catch (Exception e) {
            return error("代码分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI代码优化建议
     */
    @PreAuthorize("@ss.hasPermi('system:ai:optimization')")
    @PostMapping("/optimization")
    public AjaxResult getAiOptimization(@RequestBody Map<String, Object> requestData)
    {
        try {
            String problemId = (String) requestData.get("problemId");
            String userCode = (String) requestData.get("userCode");
            String language = (String) requestData.get("language");
            String optimizationType = (String) requestData.get("optimizationType");
            
            // 调用AI服务获取优化建议
            Map<String, Object> optimization = aiAssistantService.getOptimizationSuggestions(
                problemId, userCode, language, optimizationType);
            
            return success(optimization);
        } catch (Exception e) {
            return error("获取优化建议失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI调试帮助
     */
    @PreAuthorize("@ss.hasPermi('system:ai:debug')")
    @PostMapping("/debug")
    public AjaxResult getAiDebugHelp(@RequestBody Map<String, Object> requestData)
    {
        try {
            String problemId = (String) requestData.get("problemId");
            String userCode = (String) requestData.get("userCode");
            String language = (String) requestData.get("language");
            String errorMessage = (String) requestData.get("errorMessage");
            String testCase = (String) requestData.get("testCase");
            
            // 调用AI服务获取调试帮助
            Map<String, Object> debugHelp = aiAssistantService.getDebugHelp(
                problemId, userCode, language, errorMessage, testCase);
            
            return success(debugHelp);
        } catch (Exception e) {
            return error("获取调试帮助失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI算法解释
     */
    @PreAuthorize("@ss.hasPermi('system:ai:algorithm')")
    @PostMapping("/algorithm")
    public AjaxResult getAiAlgorithmExplanation(@RequestBody Map<String, Object> requestData)
    {
        try {
            String problemId = (String) requestData.get("problemId");
            String algorithmType = (String) requestData.get("algorithmType");
            
            // 调用AI服务获取算法解释
            Map<String, Object> explanation = aiAssistantService.getAlgorithmExplanation(problemId, algorithmType);
            
            return success(explanation);
        } catch (Exception e) {
            return error("获取算法解释失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI学习建议
     */
    @PreAuthorize("@ss.hasPermi('system:ai:learning-advice')")
    @PostMapping("/learning-advice")
    public AjaxResult getAiLearningAdvice(@RequestBody Map<String, Object> requestData)
    {
        try {
            String problemId = (String) requestData.get("problemId");
            String userLevel = (String) requestData.get("userLevel");
            String learningGoal = (String) requestData.get("learningGoal");
            
            // 调用AI服务获取学习建议
            Map<String, Object> advice = aiAssistantService.getLearningAdvice(problemId, userLevel, learningGoal);
            
            return success(advice);
        } catch (Exception e) {
            return error("获取学习建议失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI代码评分
     */
    @PreAuthorize("@ss.hasPermi('system:ai:code-score')")
    @PostMapping("/code-score")
    public AjaxResult getAiCodeScore(@RequestBody Map<String, Object> requestData)
    {
        try {
            String problemId = (String) requestData.get("problemId");
            String userCode = (String) requestData.get("userCode");
            String language = (String) requestData.get("language");
            
            // 调用AI服务进行代码评分
            Map<String, Object> score = aiAssistantService.evaluateCode(problemId, userCode, language);
            
            return success(score);
        } catch (Exception e) {
            return error("代码评分失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI相似题目推荐
     */
    @PreAuthorize("@ss.hasPermi('system:ai:similar-problems')")
    @PostMapping("/similar-problems")
    public AjaxResult getAiSimilarProblems(@RequestBody Map<String, Object> requestData)
    {
        try {
            String problemId = (String) requestData.get("problemId");
            String userLevel = (String) requestData.get("userLevel");
            Integer limit = (Integer) requestData.get("limit");
            
            // 调用AI服务获取相似题目推荐
            List<Map<String, Object>> similarProblems = aiAssistantService.getSimilarProblems(problemId, userLevel, limit);
            
            return success(similarProblems);
        } catch (Exception e) {
            return error("获取相似题目推荐失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI编程知识图谱
     */
    @PreAuthorize("@ss.hasPermi('system:ai:knowledge-graph')")
    @PostMapping("/knowledge-graph")
    public AjaxResult getAiKnowledgeGraph(@RequestBody Map<String, Object> requestData)
    {
        try {
            String topic = (String) requestData.get("topic");
            String depth = (String) requestData.get("depth");
            
            // 调用AI服务获取知识图谱
            Map<String, Object> knowledgeGraph = aiAssistantService.getKnowledgeGraph(topic, depth);
            
            return success(knowledgeGraph);
        } catch (Exception e) {
            return error("获取知识图谱失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI编程挑战
     */
    @PreAuthorize("@ss.hasPermi('system:ai:programming-challenges')")
    @PostMapping("/programming-challenges")
    public AjaxResult getAiProgrammingChallenges(@RequestBody Map<String, Object> requestData)
    {
        try {
            String userLevel = (String) requestData.get("userLevel");
            String category = (String) requestData.get("category");
            Integer count = (Integer) requestData.get("count");
            
            // 调用AI服务获取编程挑战
            List<Map<String, Object>> challenges = aiAssistantService.getProgrammingChallenges(userLevel, category, count);
            
            return success(challenges);
        } catch (Exception e) {
            return error("获取编程挑战失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI编程历史记录
     */
    @PreAuthorize("@ss.hasPermi('system:ai:history')")
    @GetMapping("/history")
    public TableDataInfo getAiHistory(String userId, String problemId, Integer pageNum, Integer pageSize)
    {
        startPage();
        AiConversation aiConversation = new AiConversation();
        aiConversation.setUserId(userId);
        aiConversation.setProblemId(problemId);
        List<AiConversation> list = aiAssistantService.selectAiConversationList(aiConversation);
        return getDataTable(list);
    }

    /**
     * 保存AI对话记录
     */
    @PreAuthorize("@ss.hasPermi('system:ai:conversation')")
    @PostMapping("/conversation")
    public AjaxResult saveAiConversation(@RequestBody Map<String, Object> requestData)
    {
        try {
            String userId = (String) requestData.get("userId");
            String problemId = (String) requestData.get("problemId");
            String question = (String) requestData.get("question");
            String answer = (String) requestData.get("answer");
            String questionType = (String) requestData.get("questionType");
            
            // 保存对话记录
            AiConversation conversation = new AiConversation();
            conversation.setUserId(userId);
            conversation.setProblemId(problemId);
            conversation.setQuestion(question);
            conversation.setAnswer(answer);
            conversation.setQuestionType(questionType);
            
            int result = aiAssistantService.insertAiConversation(conversation);
            
            return toAjax(result);
        } catch (Exception e) {
            return error("保存对话记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI助手配置
     */
    @PreAuthorize("@ss.hasPermi('system:ai:config')")
    @GetMapping("/config")
    public AjaxResult getAiAssistantConfig(String userId)
    {
        try {
            Map<String, Object> config = aiAssistantService.getAssistantConfig(userId);
            return success(config);
        } catch (Exception e) {
            return error("获取配置失败：" + e.getMessage());
        }
    }

    /**
     * 更新AI助手配置
     */
    @PreAuthorize("@ss.hasPermi('system:ai:config')")
    @PutMapping("/config")
    public AjaxResult updateAiAssistantConfig(@RequestBody Map<String, Object> requestData)
    {
        try {
            String userId = (String) requestData.get("userId");
            Map<String, Object> config = (Map<String, Object>) requestData.get("config");
            
            int result = aiAssistantService.updateAssistantConfig(userId, config);
            
            return toAjax(result);
        } catch (Exception e) {
            return error("更新配置失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI助手统计信息
     */
    @PreAuthorize("@ss.hasPermi('system:ai:stats')")
    @GetMapping("/stats")
    public AjaxResult getAiAssistantStats(String userId, String timeRange)
    {
        try {
            Map<String, Object> stats = aiAssistantService.getAssistantStats(userId, timeRange);
            return success(stats);
        } catch (Exception e) {
            return error("获取统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 导出AI对话记录
     */
    @PreAuthorize("@ss.hasPermi('system:ai:export')")
    @Log(title = "AI对话记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, String userId, String problemId)
    {
        AiConversation aiConversation = new AiConversation();
        aiConversation.setUserId(userId);
        aiConversation.setProblemId(problemId);
        List<AiConversation> list = aiAssistantService.selectAiConversationList(aiConversation);
        ExcelUtil<AiConversation> util = new ExcelUtil<AiConversation>(AiConversation.class);
        util.exportExcel(response, list, "AI对话记录数据");
    }
} 